// 查看历史记录页面
<template>
  <header class="Headerclass">
    <img
      src="../../../../images//fae98107-94c4-47d1-ab04-f3e21ba7d864.png"
      alt=""
      @click="recordingGoBack"
    />
    <h1>{{ id }}</h1>
  </header>
  <main>
    <!-- 聊天记录 -->
    <div class="Chatrecord">
      <div v-for="item in chrt" :key="item.id">
        <div v-for="item1 in chrtData" :key="item1.id">
          <div class="Ben1">
            <div class="Tou">待放图</div>
            <div class="Lisine">
              <div class="Namel">{{ userData }}</div>
              <div class="Text">{{ item1.content }}</div>
            </div>
          </div>
        </div>
        <div class="Ben">
          <div class="Tou">待放图</div>
          <div class="Lisine">
            <div class="Namel">{{ user }}</div>
            <div class="Text">{{ item.content }}</div>
          </div>
        </div>
      </div>
    </div>
    <input type="text" v-model="newMessage" @keyup.enter="sendMessage" class="ButtonEl" />
  </main>
</template>

<script setup>
import { useRouter, useRoute } from "vue-router";
import { reactive, ref, watch } from "vue";
import { Liaotain } from "../../../../utils/api/spancall";
import { HLiaotain } from "../../../../utils/api/spancall";
const router = useRouter();
const route = useRoute();
const id = route.params.id;
let user = ref("");
let pid = ref("");
let chrt = reactive([]);
let socket = null;
let chrtData = reactive([]);
let userData = ref("");
const newMessage = ref("");
const recordingGoBack = () => {
  router.go(-1);
};
const DoctorChat_id = localStorage.getItem("Doctorchat");
Liaotain({ DoctorChat_id }).then(async (res) => {
  console.log(res, "数据");
  // 获取聊天数据
  user.value = res.data.data.user;
  pid.value = res.data.data.chrt[0].pid;
  // 初始连接 WebSocket
  const url = `ws://localhost:8080?pid=${pid.value}&did=${res.data.data.chrt[0].chatData[0].chatData_id}`;
  // const url = `http://172.27.6.151:12380?pid=${pid.value}&did=${res.data.data.chrt[0].chatData[0].chatData_id}`;
  connectSocket(url);
  Object.assign(chrt, res.data.data.chrt[0].chatData);
});

watch(pid, (newPid, oldPid) => {
  const PatientChat_id = newPid;

  HLiaotain({ PatientChat_id }).then((res) => {
    console.log(res, "123456");
    userData.value = res.data.data.user;
    Object.assign(chrtData, res.data.data.chrt[0].chatData);
  });
});

// 尝试连接 WebSocket
function connectSocket(url) {
  if (socket) {
    socket.close(); // 如果已经存在连接，先关闭它
  }
  socket = new WebSocket(url);

  socket.onopen = function (event) {
    console.log("连接到 WebSocket 服务器");
  };

  socket.onmessage = function (event) {
    const data = JSON.parse(event.data);
    chrt.push({
      content: data.content,
      // 如果有其他需要的字段，可以在这里添加
    });
  };

  socket.onclose = function (event) {
    console.log("WebSocket 连接已关闭", event);
    // 延迟一段时间后重连
    setTimeout(function () {
      connectSocket(url);
    }, 1000); // 等待5秒后重连
  };

  socket.onerror = function (error) {
    console.error("WebSocket 错误：", error);
  };
}

// 发送消息的函数
const sendMessage = () => {
  if (newMessage.value.trim() !== "") {
    const messageData = {
      sender: user.value,
      content: newMessage.value,
    };
    // 发送消息到服务器，但注意服务器可能期望接收整个对象，而不仅仅是内容
    // 如果服务器只期望内容，则使用 messageData.content
    socket.send(messageData.content); // 发送整个对象
    // 如果服务器只处理内容，则使用以下代码
    // socket.send(messageData.content);

    // 将消息添加到本地聊天记录中（如果需要）
    chrt.push(messageData);

    // 清空输入框
    newMessage.value = "";
  }
};
</script>

<style lang="scss">
.Headerclass {
  display: flex;
  width: 100%;
  align-items: center;
  img {
    height: 40px;
  }
  h1 {
    margin-left: 40%;
    transform: translateX(-40%);
  }
}
main {
  height: 100%;
  background: #e7e7e7;
  .ButtonEl {
    position: absolute;
    bottom: 0;
    width: 80%;
    border-radius: 10px;
    border: 1px solid #000;
    margin-left: 30%;
    transform: translateX(-25%);
  }
}
.Chatrecord {
  height: 80%;
  overflow: auto;
}
.Ben {
  display: flex;
  flex-direction: row-reverse;
  padding-top: 40px;
  height: 80%;
  .Lisine {
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    .Namel {
      margin-right: 25px;
      margin-top: 20px;
    }
    .Text {
      min-width: 20px;
      max-width: 200px;
      min-height: 20px;
      text-align: center;
      word-wrap: break-word;
      word-break: normal;
      margin-top: 5px;
      margin-right: 20px;
      border-radius: 10px;
      padding: 15px;
      font-size: 20px;
      align-items: center;
      background: rgba(228, 99, 99, 0.867);
    }
  }
  .Tou {
    display: flex;
    margin-right: 10px;
    align-items: center;
    border: 2px solid #fff;
    border-radius: 30px;
    width: 50px;
    height: 50px;
    font-size: 16px;
  }
}
.Ben1 {
  display: flex;
  flex-direction: row;
  margin-left: 5px;
  padding-top: 40px;
  height: 80%;
  .Lisine {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    .Namel {
      margin-right: 25px;
      margin-top: 20px;
    }
    .Text {
      min-width: 20px;
      max-width: 200px;
      min-height: 20px;
      text-align: center;
      word-wrap: break-word;
      word-break: normal;
      margin-top: 5px;
      margin-right: 20px;
      border-radius: 10px;
      padding: 15px;
      font-size: 20px;
      align-items: center;
      background: rgba(228, 99, 99, 0.867);
    }
  }
  .Tou {
    display: flex;
    margin-right: 10px;
    align-items: center;
    border: 2px solid #fff;
    border-radius: 30px;
    width: 50px;
    height: 50px;
    font-size: 16px;
  }
}
</style>
